package com.lh.common.utils;

import java.util.ArrayList;
import java.util.List;

/**
 * @description: 分割list工具类
 * @author: Wudp
 * @create: 2019-11-19 11:36
 **/
public class SplitListUtils {

    /**
     * 分割list
     *
     * @param totallist
     * @return
     */
    public static <T> List<List<T>> splitList(List<T> totallist) {

        //定义每次传输条数
        int count = 1000;
        int totalCount = totallist.size();
        //计算循环次数
        int num = totalCount % count == 0 ? totalCount / count : totalCount / count + 1;
        //while循环判断标志，每次循环后加1，不能大于num
        int flag = 0;
        //list使用subList()方法的起始参数
        int fromIndex = 0;
        //list使用subList()方法的结束参数
        int toIndex = 0;
        //定义返回对象
        List<List<T>> totalList = new ArrayList<>(num);
        while (flag < num) {
            fromIndex = toIndex;
            toIndex = fromIndex + count;
            //定义分割后的接受对象
            List<T> subList = new ArrayList<>();
            if (toIndex < totalCount) {
                subList = totallist.subList(fromIndex, toIndex);
            } else {
                subList = totallist.subList(fromIndex, totalCount);
            }
            totalList.add(subList);
            flag++;
        }
        return totalList;
    }
}
